package ui.gui;

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

import domein.DomeinController;

public class ObstakelPanel extends JPanel implements ActionListener {

	private ButtonGroup btnGroup;
	private JToggleButton[] cmd;
	private String[][] obstakels;
	
	public ObstakelPanel(ButtonGroup btnGroup) {
		this.btnGroup = btnGroup;
		
		this.setLayout(new FlowLayout());
		
		this.obstakels = DomeinController.getInstance().geefObstakels();
		
		this.initComponents();
	}
	
	private void initComponents() {
		cmd = new JToggleButton[obstakels.length];
		
		for(int i=0; i<obstakels.length; i++) {
			Icon icon = createIcon("assets/textures/" + obstakels[i][2]);
			
			cmd[i] = new JToggleButton(obstakels[i][0], icon);
			cmd[i].setVerticalTextPosition(AbstractButton.BOTTOM);
		    cmd[i].setHorizontalTextPosition(AbstractButton.CENTER);
			cmd[i].addActionListener(this);
			cmd[i].setToolTipText(obstakels[i][0]);
			
			btnGroup.add(cmd[i]);
			
			add(cmd[i]);
		}
		
		cmd[0].setSelected(true);
		
		DomeinController.getInstance().selecteerObstakel(obstakels[0][0]);
	}
	
	private ImageIcon createIcon(String path) {	
		BufferedImage drawImage = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
		
		try {
			BufferedImage bImage = ImageIO.read(new File(path));
			
			Graphics g = drawImage.getGraphics();
			g.drawImage(new ImageIcon(bImage).getImage(), 0, 0, 64, 64, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new ImageIcon(drawImage);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		for(int i=0; i<obstakels.length; i++) {
			if(e.getSource() == cmd[i]) {
				DomeinController.getInstance().selecteerObstakel(obstakels[i][0]);
			}
		}
	}
}
